package com.caipin.netty.decoder;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;


/**
 * @Author: zhunian0322@163.com
 * @DateTime: 2020-03-17 15:11
 * @Description: TODO
 */
@Slf4j
public class StickyBagHandler extends ByteToMessageDecoder {

    private static StringBuilder sb = new StringBuilder();


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        if (in.getByte(in.readerIndex()) == 0x5B) {
            for (int i = 1; i < in.readableBytes(); i++) {
                if (in.getByte(i + in.readerIndex()) == 0x5D) {
                    out.add(in.readBytes(i + 1));
                    break;
                }
            }
        } else if (in.getByte(in.readerIndex()) == 0x7B) {
            int startFlag = 1;
            int endFlag = 0;

            for (int i = 1; i < in.readableBytes(); i++) {
                if (in.getByte(i + in.readerIndex()) == 0x7B) {
                    startFlag++;
                } else if (in.getByte(i + in.readerIndex()) == 0x7D) {
                    endFlag++;
                }

                if (startFlag == endFlag) {
                    out.add(in.readBytes(i + 1));
                    break;
                }
            }
        }
    }
}
